<?php
/*
 * 短信服务发送
 */
class Sms extends CComponent {
	public function init() {
	
	}
	/**
	 * 生产验证码
	 */
	public function genCode(){
		return rand(0, 9).rand(0, 9).rand(0, 9).rand(0, 9);
	}
	
	/**
	 * 发送短信邀请码
	 * @param string $cellphoneNumber
	 */
	public function sendCode($cellphoneNumber) {
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "http://api.weimi.cc/2/sms/send.html");
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($ch, CURLOPT_SSLVERSION , 3);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		$code = $this -> genCode();
		curl_setopt($ch, CURLOPT_POSTFIELDS, 'uid=WImANNoppPuj&cid=NmtRyAocBwFj&pas=jqumjc6x&mob='.$cellphoneNumber.'&type=json&con='.urlencode('【白鹿】短信验证码 %P% ，五分钟内有效').'&p1='.$code);
		$res = curl_exec( $ch );
		curl_close( $ch );
		if($res){
			$data_msg = json_decode($res);
			if($data_msg -> code ==0){
				$_SESSION['cellphone_code']= array('code'=>$code,'dateline'=>time());
			}
		}
	}
	
	
	
	//$sms -> verfifyCode('6803')
	/**
	 * 手机验证码验证
	 * @param string $code
	 */
	public function verfifyCode($code){
		$now = time();
		$fivemin = 5 * 60;
		if(isset($_SESSION['cellphone_code'])){
			$cellphone_code_cfg = $_SESSION['cellphone_code'];
			$dateline = $cellphone_code_cfg['dateline'];
			$dateline += $fivemin;
			if($now < $dateline){
				if(strtolower($code) == $cellphone_code_cfg['code']){
					unset($_SESSION['cellphone_code']);
					return true;
				}
			}
			return false;
		}else{
			return false;
		}
	}
	
}